package com.yh.controller;



import com.yh.pojo.Books;
import com.yh.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;

import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/book")
public class BookController {
    //controller层 调用service层
    @Autowired  //注入service层的bean
    @Qualifier("BookServiceImpl")
    private BookService bookService;


    //查询全部的书籍，并且返回到一个书籍展示页面
    @RequestMapping("/allBook")
    public String list(Model model){
        List<Books> books = bookService.queryAllBook();
        //iter
        for (Books book : books) {

        }


        //1、
        for (Books book : books) {

        }




        model.addAttribute("list",books);

        return "allBook";
    }

    // 跳转到新增书籍页面
    @RequestMapping("/toAddBook")
    public String toAddPage(){
        return "addBook";
    }
    //增加书籍

    @RequestMapping("/addBook")
    public String addBook(Books books){
        System.out.println("开始保存对象：   "+books);
        bookService.addBook(books);


        // 添加完之后，要重定向到首页
        return "redirect:/book/allBook";
    }

    //修改纾解功能
    @RequestMapping("/toUpdateBook")
    public String toUpdateBook(Model model, int id) {
//        获取前端拼接过来的id参数
        Books book = bookService.queryBookById(id);
        System.out.println(book);
        model.addAttribute("QBook",book );
        return "updateBook";
    }

    @RequestMapping("/updateBook")
    public String updateBook(Model model, Books book) {
        System.out.println("要修改的数据是："+book);
        int i = bookService.updateBook(book);
        if(i>0){
            System.out.println("数据添加成功。。。。。。。。");
        }
        Books books = bookService.queryBookById(book.getBookID());
        model.addAttribute("books", books);
        return "redirect:/book/allBook";
    }

    //删除书籍  restful风格  PathVariable里面的值就是对应上面路径{bookId}  得一致
    @RequestMapping("/del/{bookId}")
    public String deleteBook(@PathVariable("bookId") int id) {
        bookService.deleteBookById(id);
        return "redirect:/book/allBook";
    }



    // 搜索框功能  前端会传入一个书籍的名字
    @RequestMapping("/queryBookName")
    public String queryBookName(String queryBookName,Model model){
        Books books = bookService.queryBookByName(queryBookName);

        List<Books> list =new ArrayList<Books>();
        list.add(books);

//        如果没有查到关于名字的书籍，那么就直接重新查所有
        if (books ==null){
            list =bookService.queryAllBook();
            model.addAttribute("msg","未查询指定书籍");
//
        }


        model.addAttribute("list",list);

        return "allBook";

    }
}
